package com.xiang.xian.array;

public class MyArrayList<E> {
    private Object[] data;
    private int size;

    public MyArrayList() {
        data = new Object[10]; // 初始容量
        size = 0;
    }
    public MyArrayList(int capacity) {
        data = new Object[capacity]; // 初始容量
        size = 0;
    }

    public void add(int index, E element) {
        if (index > size || index < 0) {
            throw new IndexOutOfBoundsException();
        }
        if (size == data.length) {
            // 扩容逻辑可以在这里处理
        }
        System.arraycopy(data, index, data, index + 1, size - index);
        data[index] = element;
        size++;
    }

    public MyArrayList<E> copy() {
        MyArrayList<E> newList = new MyArrayList<>();
        newList.ensureCapacity(this.size);
        System.arraycopy(this.data, 0, newList.data, 0, this.size);
        newList.size = this.size;
        return newList;
    }

    public void ensureCapacity(int minCapacity) {
        if (minCapacity > data.length) {
            Object[] newData = new Object[Math.max(minCapacity, (data.length * 3) / 2 + 1)];
            System.arraycopy(data, 0, newData, 0, data.length);
            data = newData;
        }
    }

    public void add(E element) {
        if (size == data.length) {
            ensureCapacity(size + 1);
        }
        data[size++] = element;
    }
}